package com.iflytek.autofly.setting.biz.more;

import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemProperties;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.iflytek.autofly.radioservice.util.RadioServiceCons;
import com.iflytek.autofly.setting.R;
import com.iflytek.autofly.setting.biz.base.BaseFragment;
import com.iflytek.autofly.setting.biz.base.CommonRadioButtonBean;
import com.iflytek.autofly.setting.biz.base.CommonRadioGroupAdpt;
import com.iflytek.autofly.setting.biz.system.FlyDatePickerDialog;
import com.iflytek.autofly.setting.biz.system.FlyRadioManager;
import com.iflytek.autofly.setting.biz.system.FlyTimePickerDialog;
import com.iflytek.autofly.setting.biz.system.TimeControl;
import com.iflytek.autofly.setting.widget.InnerListView;
import com.iflytek.autofly.utils.FlyLog;
import com.iflytek.sunflower.FlowerCollector;

import java.util.Calendar;

/**
 * <b>Description: </b>更多设置的fragment<br/>
 * <b>Change History:</b><br/>
 * <table border="1">
 * <tr>
 * <td><b>user</b></td>
 * <td><b>date</b></td>
 * <td><b>time</b></td>
 * <td><b>reason</b></td>
 * </tr>
 * <tr>
 * <td>qiliu5@iflytek.com</td>
 * <td>2015年10月14日</td>
 * <td>上午11:34:14</td>
 * <td>创建此文件</td>
 * </tr>
 * </table>
 *
 * @author qiliu5@iflytek.com
 */
public class MoreFragment extends BaseFragment implements FlyRadioManager.IFlyRadioListener {
    protected static final String TAG = "MoreFragment";
    private static final String[] CMD = {};

    private static final String KEY_VIDEO_SETTING = "persist.sys.video.setting";
    private static final int INDEX_VIDEOSETTING_VOICE = 0;
    private static final int INDEX_VIDEOSETTING_NORMAL = 1;
    private static final int INDEX_VIDEOSETTING_FORBID = 2;

    TimeControl mTimeControl;
    private ToggleButton mTimeFormat24Tbn;
    private TextView mAutoTimeDescTv;
    private ToggleButton mAutoTimeTbn;
    private TextView mDataTv;
    private TextView mTimeTv;

    private TextView mRadioModeValueTv;
    private InnerListView mRadioModeList;
    private FlyRadioManager mRadio;

    private TextView mVideoSettingValueTv;
    private InnerListView mVideoSettingList;
    private int mVideoSetting;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = super.onCreateView(inflater, container, savedInstanceState);
        init(view);
        return view;
    }

    @Override
    public void onDestroy() {
        getActivity().unregisterReceiver(mReceiver);
        FlyRadioManager.unregisterListener();
        mRadio = null;

        super.onDestroy();
    }

    private void init(View v) {
        addUnit(R.layout.timesetting, R.layout.timesetting_sub, new OnExpandChangeListener() {
            @Override
            public void onExpandChanged(boolean isExpanded) {
                if (isExpanded) {
                    mAutoTimeDescTv.setVisibility(View.GONE);
                } else {
                    mAutoTimeDescTv.setVisibility(View.VISIBLE);
                }
            }
        }, null);
        addUnit(R.layout.timeformat);
        addUnit(R.layout.radiomode, R.layout.radiomode_sub, new OnExpandChangeListener() {
            @Override
            public void onExpandChanged(boolean isExpanded) {
                if (isExpanded) {
                    mRadioModeValueTv.setVisibility(View.GONE);
                } else {
                    mRadioModeValueTv.setVisibility(View.VISIBLE);
                }
            }
        }, null);
        addHiddenUnit(R.layout.videosetting, R.layout.videosetting_sub, new OnExpandChangeListener() {
            @Override
            public void onExpandChanged(boolean isExpanded) {
                if (isExpanded) {
                    mVideoSettingValueTv.setVisibility(View.GONE);
                } else {
                    mVideoSettingValueTv.setVisibility(View.VISIBLE);
                }
            }
        }, null);
        // FIXME: 2016/1/4
        // temp solution.
        // 点击最后一个item，切换，再点开，箭头状态不对，临时添加一个不可见item解决一下
        addHiddenUnit(R.layout.aboutsystem);

        // Register for time ticks and other reasons for time change
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_TIME_TICK);
        filter.addAction(Intent.ACTION_TIME_CHANGED);
        filter.addAction(Intent.ACTION_TIMEZONE_CHANGED);
        getActivity().registerReceiver(mReceiver, filter);
        mRadio = FlyRadioManager.registerListener(getActivity(), this);

        mTimeControl = new TimeControl(getActivity());

        mAutoTimeDescTv = (TextView) v.findViewById(R.id.sys_time_desc_tv);
        mAutoTimeTbn = (ToggleButton) v.findViewById(R.id.sys_time_switch_tbn);
        mAutoTimeTbn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.more) + "-" + getString(R.string.sys_time_autoset), "" + isChecked);
                mTimeControl.setAutoTime(isChecked);
                if (isChecked) {
                    collapse(0);
                    setExpandable(0, false);
                } else {
                    setExpandable(0, true);
                    expand(0);
                }
            }
        });
        mAutoTimeTbn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });
        mDataTv = (TextView) v.findViewById(R.id.sys_time_date_value_tv);
        RelativeLayout dateRl = (RelativeLayout) v.findViewById(R.id.sys_time_date_rl);
        dateRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar calendar = Calendar.getInstance();
                Dialog d;
                d = new FlyDatePickerDialog(getActivity(),
                        new FlyDatePickerDialog.OnDateSetListener() {
                            @Override
                            public void onDateSet(com.iflytek.autofly.flypicker.DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                                mTimeControl.setDate(year, monthOfYear, dayOfMonth);
                                updateDateUI();
                            }
                        },
                        calendar.get(Calendar.YEAR),
                        calendar.get(Calendar.MONTH),
                        calendar.get(Calendar.DAY_OF_MONTH));
                d.show();
            }
        });
        mTimeTv = (TextView) v.findViewById(R.id.sys_time_time_value_tv);
        RelativeLayout timeRl = (RelativeLayout) v.findViewById(R.id.sys_time_time_rl);
        timeRl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(final View v) {
                final Calendar calendar = Calendar.getInstance();
                Dialog d;
                d = new FlyTimePickerDialog(getActivity(),
                        new FlyTimePickerDialog.OnTimeSetListener() {
                            @Override
                            public void onTimeSet(com.iflytek.autofly.flypicker.TimePicker view, int hourOfDay, int minute) {
                                mTimeControl.setTime(hourOfDay, minute);
                                updateTimeUI();

                            }

                        },
                        calendar.get(Calendar.HOUR_OF_DAY),
                        calendar.get(Calendar.MINUTE),
                        mTimeControl.getTimeFormat24());
                d.show();

            }
        });

        mTimeFormat24Tbn = (ToggleButton) v.findViewById(R.id.sys_time_format_switch_tbn);
        mTimeFormat24Tbn.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.more) + "-" + getString(R.string.sys_time_format), "" + isChecked);
                mTimeControl.setTimeFormat24(isChecked);
                updateTimeUI();
            }
        });
        mTimeFormat24Tbn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

            }
        });

        mRadioModeValueTv = (TextView) v.findViewById(R.id.sys_radiomode_value_tv);
        mRadioModeList = (InnerListView) v.findViewById(R.id.sys_radiomode_listview);
        CommonRadioGroupAdpt radioModeListAdpt = new CommonRadioGroupAdpt(getActivity());
        radioModeListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_radio_city), R.string.sys_radio_city));
        radioModeListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.sys_radio_country), R.string.sys_radio_country));
        mRadioModeList.setAdapter(radioModeListAdpt);
        mRadioModeList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.more) + "-" + getString(R.string.sys_radio), getString((int) id));
                switch ((int) id) {
                    case R.string.sys_radio_city:
                        mRadioModeValueTv.setText(getString(R.string.sys_radio_value_city));
                        if (mRadio != null) {
                            mRadio.setMode(RadioServiceCons.RadioMode.LOCAL_MODE);
                        }
                        break;
                    case R.string.sys_radio_country:
                        mRadioModeValueTv.setText(getString(R.string.sys_radio_value_country));
                        if (mRadio != null) {
                            mRadio.setMode(RadioServiceCons.RadioMode.REMOTE_MODE);
                        }
                        break;
                    default:
                }
            }
        });
        mRadio.getMode();

        mVideoSettingValueTv = (TextView) v.findViewById(R.id.more_videosetting_value_tv);
        mVideoSettingList = (InnerListView) v.findViewById(R.id.more_videosetting_listview);
        CommonRadioGroupAdpt videoSettingListAdpt = new CommonRadioGroupAdpt(getActivity());
        videoSettingListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.more_videosetting_voice), R.string.more_videosetting_voice));
        videoSettingListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.more_videosetting_normal), R.string.more_videosetting_normal));
        videoSettingListAdpt.addItem(new CommonRadioButtonBean(getString(R.string.more_videosetting_forbid), R.string.more_videosetting_forbid));
        mVideoSettingList.setAdapter(videoSettingListAdpt);
        mVideoSettingList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                FlowerCollector.onEvent(getActivity().getApplicationContext(), getString(R.string.more) + "-" + getString(R.string.more_videosetting), getString((int) id));
                if (mVideoSetting != position) {
                    mVideoSetting = position;
                    updateVideoSettingUI(position);
                    SystemProperties.set(KEY_VIDEO_SETTING, Integer.toString(position));
                }
            }
        });
    }

    public void renew() {
        boolean isAutoTime = mTimeControl.getAutoTime();
        mAutoTimeTbn.setChecked(isAutoTime);
        updateDateUI();
        updateTimeUI();

        mTimeFormat24Tbn.setChecked(mTimeControl.getTimeFormat24());

        mVideoSetting = SystemProperties.getInt(KEY_VIDEO_SETTING, 0);
        updateVideoSettingUI(mVideoSetting);
    }

    private void updateDateUI() {
        mDataTv.setText(mTimeControl.getDate());
    }

    private void updateTimeUI() {
        mTimeTv.setText(mTimeControl.getTime());
    }

    private void updateVideoSettingUI(int position) {
        switch (position) {
            case INDEX_VIDEOSETTING_VOICE:
                mVideoSettingValueTv.setText(getString(R.string.more_videosetting_voice_value));
                break;
            case INDEX_VIDEOSETTING_NORMAL:
                mVideoSettingValueTv.setText(getString(R.string.more_videosetting_normal_value));
                break;
            case INDEX_VIDEOSETTING_FORBID:
                mVideoSettingValueTv.setText(getString(R.string.more_videosetting_forbid_value));
                break;
            default:
                break;
        }
        mVideoSettingList.setItemChecked(position, true);
    }

    @Override
    public void processCommandline(String cmd) {
    }

    @Override
    public String[] getCommands() {
        return CMD;
    }

    @Override
    public void onModeChanged(final int mode) {
        if (mRadioModeList != null && mRadioModeValueTv != null) {
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    if (mRadioModeList != null && mRadioModeValueTv != null) {
                        if (mode == RadioServiceCons.RadioMode.LOCAL_MODE) {
                            mRadioModeList.setItemChecked(0, true);
                            mRadioModeValueTv.setText(getString(R.string.sys_radio_value_city));
                        } else if (mode == RadioServiceCons.RadioMode.REMOTE_MODE) {
                            mRadioModeList.setItemChecked(1, true);
                            mRadioModeValueTv.setText(getString(R.string.sys_radio_value_country));
                        } else {
                            FlyLog.e(TAG, "onModeChanged|invalid mode=" + mode);
                        }
                    }
                }
            });
        }
    }

    private BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            updateDateUI();
            updateTimeUI();
        }
    };

}
